import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

const List<String> defaultImages = [
  "https://res.gemiman.com/8ad34acd7effca4a3d3f05d8049a876b4359455d3348384980b131dbd3ec9822.png",
  "https://res.gemiman.com/a9590817692e8dcfd8e3e2f50f4f173bbc2ab2543d8ece1979d9841d2b6da70c.png",
  "https://res.gemiman.com/be0e4de65ec23033ae916ae43d799814a3c7ab9386d69417a7adcec960a07eb5.png",
  "https://res.gemiman.com/5dd97b92d34476d0f2ffd533034d548239cebbdd51f70332c67d2f2418e422c1.png",
];

const imageWidth = 1024.0;
const imageHeight = 576.0;
const imageWidthHeightRatio = imageWidth / imageHeight;

class CommonImagePickWidget extends StatefulWidget {
  final ValueChanged<List<File>>? onChange;

  const CommonImagePickWidget({super.key, this.onChange});

  @override
  State<CommonImagePickWidget> createState() => _CommonImagePickWidgetState();
}

class _CommonImagePickWidgetState extends State<CommonImagePickWidget> {
  List<File> files = [];

  _picImage() async {
    var image = await ImagePicker().pickImage(source: ImageSource.gallery);
    if (image != null) {
      setState(() {
        files = files..add(File(image.path));
        if (widget.onChange != null) {
          widget.onChange!(files);
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    var width = (MediaQuery.of(context).size.width - 10 * 4) / 3;
    var height = width / imageWidthHeightRatio;
    Widget addButton = GestureDetector(
      onTap: () {
        _picImage();
      },
      behavior: HitTestBehavior.translucent,
      child: Container(
        width: width,
        height: height,
        color: Colors.grey,
        child: Center(
          child: Icon(
            Icons.add,
            color: Colors.black,
            size: width / 3,
          ),
        ),
      ),
    );
    Widget wrapper(File file) {
      return Stack(
        clipBehavior: Clip.none,
        children: [
          Image.file(
            file,
            width: width,
            height: height,
            fit: BoxFit.cover,
          ),
          Positioned(
            right: -20,
            top: -20,
            child: IconButton(
              onPressed: () {
                setState(
                  () {
                    files = files..remove(file);
                    if (widget.onChange != null) {
                      widget.onChange!(files);
                    }
                  },
                );
              },
              icon: const Icon(
                Icons.delete_forever,
                color: Colors.red,
              ),
            ),
          ),
        ],
      );
    }

    List<Widget> list = files.map((item) => wrapper(item)).toList()
      ..add(addButton);

    return Container(
      padding: const EdgeInsets.all(10),
      child: Wrap(
        spacing: 10,
        runSpacing: 10,
        children: list,
      ),
    );
  }
}
